package com.qf.bigdata.service.impl;

import com.qf.bigdata.bean.RecommendInfo;
import com.qf.bigdata.bean.RecommendResult;
import com.qf.bigdata.repository.HBaseTemplate;
import com.qf.bigdata.repository.LRModelPredict;
import com.qf.bigdata.service.RecommendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("recommendService")
public class RecommendServiceImpl implements RecommendService {

    @Autowired
    @Qualifier("hbaseTemplate")
    private HBaseTemplate hbaseTemplate;
    @Autowired
    private LRModelPredict lrModelPredict;


    @Override
    public RecommendResult recommend(String uid) {
//        hbaseTemplate.transItemFeatureList("1647").forEach((k,v)->{
//            System.out.println(k+"|"+lrModelPredict.predictProbability(v));
//
//        });

        RecommendResult result=new RecommendResult();
        result.setCode(200);
        result.setMsg("ok");

        //[aid,user_feature+item_feature+item_embedding]
        Map<String, String> featureMap = hbaseTemplate.transItemFeatureList(uid);
        if(featureMap==null)
        {
            result.setCode(-1);
            result.setMsg("用户不存在，或者缺少相应召回物品特征");
            result.setData(null);
            return result;
        }
        List<RecommendInfo> data=new ArrayList<>();
        for (Map.Entry<String,String> entry:featureMap.entrySet()) {
            RecommendInfo recommendInfo = new RecommendInfo();
            recommendInfo.setAid( Long.parseLong(entry.getKey()));
            recommendInfo.setProbability(lrModelPredict.predictProbability(entry.getValue()));
            data.add(recommendInfo);
        }
        //倒排序
        Collections.sort(data, new Comparator<RecommendInfo>() {
            @Override
            public int compare(RecommendInfo o1, RecommendInfo o2) {
                if(o1.getProbability()==o2.getProbability())
                    return 0;
                else
                    return o1.getProbability()>o2.getProbability()?-1:1;
            }
        });
        result.setData(data);
        return result;
    }
}
